import logging
import os
from datetime import datetime
from logging.handlers import RotatingFileHandler

from config_manager import ConfigManager


class LoggerConfig:
    def __init__(self):
        self.config = ConfigManager()
        self.log_enabled = self.config.get_log_enabled()
        self.log_dir = "logs"
        self.max_bytes = 5 * 1024 * 1024  # 5MB
        self.backup_count = 100
        self._initialized = False

    def setup_logger(self):
        if not self.log_enabled:
            return
        # 先移除所有 root logger 的 handler
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            handler.close()
            root_logger.removeHandler(handler)
        if not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir)
        log_filename = os.path.join(self.log_dir, f"bastion_tool_{datetime.now().strftime('%Y%m%d')}.log")
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                RotatingFileHandler(
                    log_filename,
                    maxBytes=self.max_bytes,
                    backupCount=self.backup_count,
                    encoding='utf-8'
                ),
                logging.StreamHandler()
            ]
        )
        self._initialized = True

    def get_logger(self, name):
        if not self._initialized and self.log_enabled:
            self.setup_logger()
        logger = logging.getLogger(name)
        if not self.log_enabled:
            logger.addHandler(logging.NullHandler())
            logger.propagate = False
        return logger

    def release_all_log_files(self):
        import logging
        # 释放所有自定义 logger
        for logger_name in [
            'BastionTool', 'AutoLogin', 'BastionLoader', 'UI', 'MainWindow'
        ]:
            logger = logging.getLogger(logger_name)
            for handler in logger.handlers[:]:
                try:
                    handler.close()
                except Exception:
                    pass
                logger.removeHandler(handler)
        # 释放 root logger
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            try:
                handler.close()
            except Exception:
                pass
            root_logger.removeHandler(handler)

# 全局日志器实例
logger_config = LoggerConfig()
app_logger = logger_config.get_logger('BastionTool')
auto_login_logger = logger_config.get_logger('AutoLogin')
bastion_loader_logger = logger_config.get_logger('BastionLoader')
ui_logger = logger_config.get_logger('UI')
main_window_logger = logger_config.get_logger('MainWindow')